For loops is a looping mechanism in Python that will loop over an iterator.
An iterator is defined as
An iterator is an object that contains a countable number of values that can be traversed through
Source: https://www.w3schools.com/python/python_iterators.asp
I explain for loops using a chore list. At its basics, a chore list is a list of values that you go through in a set time frame. Chores are typically done one by one until you get to the end. If we were to put my chore list into Python:
my_chore_list = ['walking dogs', 'emptying dishwasher', 'taking out trash', 'mowing lawn', 'getting gas', 'cleaning cars']
for chore in my_chore_list:
print(f'I am currently: {chore}')
When you run this loop, as an example
I am currently: walking dogs I am currently: emptying dishwasher I am currently: taking out trash I am currently: mowing lawn I am currently: getting gas I am currently: cleaning cars
It iterated over the items in the list and printed each out.With the definition of an iterator in mind, a string, dictionary, set, tuple, and a list can be iterated over. A dictionary is the only exception in this case. When you iterate over a dictionary, it may not produce the output you want. However, integers are the only items that in Python, can not be iterated over. In integers, there is only 1 item. Some examples of iterators are below:
Iterating a list
lst = [1,2,3,4]
for num in lst:
print(num)
Running this would return
1
2
3
4
Iterating a string
s = "The cat"
for l in s:
print(l)
This would return:
T h e
c a t
Iterating a dictionary
In a dictionary, things start to get interesting. If we just run the for loop as we did above:
dict = {'k1':1, 'k2':2, 'k3':3}
for item in dict:
print(item)
This would return:
k1
k2
k3
All we get back are the keys. We can use the dictionary methods in Python Dictionaries to pull back what we want from a dictionary.
By default, the for loops assume you want to iterate over a dictionary’s keys. What if you wanted to iterate over the values?
dict = {'k1':'One', 'k2':'Two', 'k3':'Three'}
for blue in dict.values():
print(blue)
This would return:
One
Two
Three
However, what if both keys and values are needed?
dict = {'k1':'One', 'k2':'Two', 'k3':'Three'}
for blue in dict.items():
print(blue)
This would return
('k1', 'One')
('k2', 'Two')
('k3', 'Three')
We get the result in a tuple, just like we would if we ran .items()
on the dictionary variable directly. With this, we can do something called tuple unpacking, where we can take each part of the dictionary, the key, and the value and assign them to a variable to print out:
dict = {'k1':'One', 'k2':'Two', 'k3':'Three'}
for cat,dog in dict.items():
print(dog)
print(cat)
This would return
One
k1
Two
k2
Three
k3
In the above, we take variable names cat and dog and pass them as variables to unpack dict.items(). The variable cat would be the keys, and the variable dog would be the values.
In the above, I used both items of the dictionary. What if you wanted to do something only if you hit a specific dictionary key? We can add an if statement to our for loop. One way we can do it is by slicing. With .items(), we are getting a tuple back:
dict = {'k1':'One', 'k2':'Two', 'k3':'Three'}
for key in dict.items():
if key[0] == 'k2':
print(key[1])
This would return
Two
We can use tuple unpacking right from the start:
dict = {'k1':'One', 'k2':'Two', 'k3':'Three'}
for key,value in dict.items():
if key == 'k3':
print(value)
This would return
Three